﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;
using System.Windows.Data;

namespace Fayshine.VA.Views.SearchStatistics.Week
{
    public partial class WeekDayShopCompare : Page
    {
        private WeekReportViewModel m_ViewModel;

        public WeekDayShopCompare()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(WeekDayShopCompare_Loaded);
        }

        private void WeekDayShopCompare_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            startDatePicker.SelectedDate = DateTime.Now;

            m_ViewModel = new WeekReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                isIn = cmbInorOut.SelectedIndex == 0 ? true : false;
                string subTitle = cmbInorOut.SelectedIndex == 0 ? "一周每日进客流对比" : "一周每日出客流对比";
                RenderAs renderAs = cmbStyle.SelectedIndex == 0 ? RenderAs.Line : RenderAs.Column;

                DateTime dateTime = new DateTime(startDatePicker.SelectedDate.Value.Year, startDatePicker.SelectedDate.Value.Month,
                                          startDatePicker.SelectedDate.Value.Day);
                DateTime startTime = dateTime;
                DateTime endTime = dateTime;
                m_ViewModel.GetWeekStartAndEndTime(dateTime, out startTime, out endTime);

                string title1 = GetChartSubTitle();
                Title vcChart1Title = new Visifire.Charts.Title();
                vcChart1Title.Text = startTime.ToShortDateString() + "至" + endTime.AddDays(-1).ToShortDateString() + title1 + subTitle;
                vcChart1.Titles.Add(vcChart1Title);

                List<HistoryPassengerFlow> historyPassengerFlows = new List<HistoryPassengerFlow>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                List<int> monitorAreaIDs = new List<int>();
                selectAreaExt.each(s => { monitorAreaIDs.Add(s.ID); });
                bool isSingleArea = monitorAreaIDs.Count == 1 ? true : false;
                if (isSingleArea)
                {
                    var topAreaGate = m_ViewModel.MonitorAreaGateExts.Where(m => m.TypeID == 1).FirstOrDefault();
                    if (topAreaGate != null)
                    {
                        List<int> ids = new List<int>();
                        if (topAreaGate.IsSelected)
                        {
                            ids = m_ViewModel.GetGateIDsByArea(topAreaGate.ID);
                        }
                        else
                        {
                            ids = m_ViewModel.MonitorAreaGateExts.Where(m => m.IsSelected && m.TypeID != 1).Select(mm => mm.ID).ToList();
                        }
                        ids = ids.OrderBy(i => i).ToList();
                        ids.each(id =>
                        {
                            var source = m_ViewModel.GetWeekHistoryPassengerFlowByGate(isSingleArea, id, dateTime);
                            vcChart1.Series.Add(GetDataSeries(m_ViewModel.GetGateName(id), isIn, renderAs, source));
                        });
                    }
                }
                else
                {
                    selectAreaExt.each(s =>
                    {
                        var source = m_ViewModel.GetWeekHistoryPassengerFlowByGate(isSingleArea, s.ID, dateTime);
                        vcChart1.Series.Add(GetDataSeries(s.Name, isIn, renderAs, source));
                    });
                }

                string columnHeader1 = GetShotDateStringForWeek(startTime, endTime, DayOfWeek.Monday) + "\r\n" + GetWeekDayString(DayOfWeek.Monday);
                string columnHeader2 = GetShotDateStringForWeek(startTime, endTime, DayOfWeek.Tuesday) + "\r\n" + GetWeekDayString(DayOfWeek.Tuesday);
                string columnHeader3 = GetShotDateStringForWeek(startTime, endTime, DayOfWeek.Wednesday) + "\r\n" + GetWeekDayString(DayOfWeek.Wednesday);
                string columnHeader4 = GetShotDateStringForWeek(startTime, endTime, DayOfWeek.Thursday) + "\r\n" + GetWeekDayString(DayOfWeek.Thursday);
                string columnHeader5 = GetShotDateStringForWeek(startTime, endTime, DayOfWeek.Friday) + "\r\n" + GetWeekDayString(DayOfWeek.Friday);
                string columnHeader6 = GetShotDateStringForWeek(startTime, endTime, DayOfWeek.Saturday) + "\r\n" + GetWeekDayString(DayOfWeek.Saturday);
                string columnHeader7 = GetShotDateStringForWeek(startTime, endTime, DayOfWeek.Sunday) + "\r\n" + GetWeekDayString(DayOfWeek.Sunday);

                this.dataGrid.Columns.Clear();

                DataGridTextColumn titleColumn = new DataGridTextColumn();
                titleColumn.Header = string.Empty;
                titleColumn.Binding = new Binding("DisplayTitle");
                titleColumn.Width = new DataGridLength(100);
                this.dataGrid.Columns.Add(titleColumn);

                DataGridTextColumn column1 = new DataGridTextColumn();
                column1.Header = columnHeader1;
                column1.Width = new DataGridLength(100);

                DataGridTextColumn column2 = new DataGridTextColumn();
                column2.Header = columnHeader2;
                column2.Width = new DataGridLength(100);

                DataGridTextColumn column3 = new DataGridTextColumn();
                column3.Header = columnHeader3;
                column3.Width = new DataGridLength(100);

                DataGridTextColumn column4 = new DataGridTextColumn();
                column4.Header = columnHeader4;
                column4.Width = new DataGridLength(100);

                DataGridTextColumn column5 = new DataGridTextColumn();
                column5.Header = columnHeader5;
                column5.Width = new DataGridLength(100);

                DataGridTextColumn column6 = new DataGridTextColumn();
                column6.Header = columnHeader6;
                column6.Width = new DataGridLength(100);

                DataGridTextColumn column7 = new DataGridTextColumn();
                column7.Header = columnHeader7;
                column7.Width = new DataGridLength(100);
                if (isIn)
                {
                    column1.Binding = new Binding("MonDayInCount");
                    column2.Binding = new Binding("TueDayInCount");
                    column3.Binding = new Binding("WedDayInCount");
                    column4.Binding = new Binding("ThuDayInCount");
                    column5.Binding = new Binding("FriDayInCount");
                    column6.Binding = new Binding("SatDayInCount");
                    column7.Binding = new Binding("SunDayInCount");
                }
                else
                {
                    column1.Binding = new Binding("MonDayOutCount");
                    column2.Binding = new Binding("TueDayOutCount");
                    column3.Binding = new Binding("WedDayOutCount");
                    column4.Binding = new Binding("ThuDayOutCount");
                    column5.Binding = new Binding("FriDayOutCount");
                    column6.Binding = new Binding("SatDayOutCount");
                    column7.Binding = new Binding("SunDayOutCount");
                }

                this.dataGrid.Columns.Add(column1);
                this.dataGrid.Columns.Add(column2);
                this.dataGrid.Columns.Add(column3);
                this.dataGrid.Columns.Add(column4);
                this.dataGrid.Columns.Add(column5);
                this.dataGrid.Columns.Add(column6);
                this.dataGrid.Columns.Add(column7);

                var source2 = m_ViewModel.WeekPassengerFlows.OrderBy(w => w.DisplayTitle);
                this.dataGrid.ItemsSource = source2;
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = false;

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                }
            });
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            m_ViewModel.AreaExtends.each(a => a.IsSelected = true);

            string msg = string.Empty;
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime dateTime = new DateTime(startDatePicker.SelectedDate.Value.Year, startDatePicker.SelectedDate.Value.Month,
                                                 startDatePicker.SelectedDate.Value.Day);
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                m_ViewModel.RefreshWeekAllShopReport(true, dateTime);
            }
        }

        private DataSeries GetDataSeries(string title, bool isIn, RenderAs randerAs, List<HistoryPassengerFlow> source)
        {
            DataSeries series = ChartHelper.GetDataSeries(randerAs, title, ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            if (isIn)
            {
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            }
            else
            {
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            }
            series.DataSource = source;

            return series;
        }

        private string GetChartSubTitle()
        {
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            return title1;
        }

        private string GetWeekDayString(DayOfWeek dayOfWeek)
        {
            string weekDay = "星期一";
            switch (dayOfWeek)
            {
                case DayOfWeek.Sunday:
                    weekDay = "星期日";
                    break;
                case DayOfWeek.Monday:
                    weekDay = "星期一";
                    break;
                case DayOfWeek.Tuesday:
                    weekDay = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    weekDay = "星期三";
                    break;
                case DayOfWeek.Thursday:
                    weekDay = "星期四";
                    break;
                case DayOfWeek.Friday:
                    weekDay = "星期五";
                    break;
                case DayOfWeek.Saturday:
                    weekDay = "星期六";
                    break;
            }

            return weekDay;
        }

        private string GetShotDateStringForWeek(DateTime start, DateTime end, DayOfWeek dayOfWeek)
        {
            DateTime a = start;

            while (start <= end)
            {
                if (start.DayOfWeek == dayOfWeek)
                {
                    a = start;
                    break;
                }
                start = start.AddDays(1);
            }

            return a.Month + "-" + a.Day;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
